#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"

using namespace std;
#define NUM 1024
namespace TCPClient
{
	enum
	{
		SOCK_ERR = 1,
		BIND_ERR,
		CONNECT_ERR,
	};

	class Client
	{
	public:
		Client(const string &ip, const uint16_t port)
			: _ip(ip), _port(port), sock_fd(-1)
		{
		}

		//  作为客户端，也需要初始化自己的套接字
		void InitClient()
		{
			sock_fd = socket(AF_INET, SOCK_STREAM, 0);
			if (sock_fd == -1)
			{
				logMessage(FATAL, "socket create failed!");
				exit(SOCK_ERR);
			}
			logMessage(NORMAL, "socket create success");
		}

		// TCP客户端的启动
		void start()
		{
			struct sockaddr_in sever;
			memset(&sever, 0, sizeof(sever));

			sever.sin_family = AF_INET;
			sever.sin_port = htons(_port);
			sever.sin_addr.s_addr = inet_addr(_ip.c_str());

			// 填写完毕，开始connect
			if (connect(sock_fd, (sockaddr *)&sever, sizeof(sever)) != 0)
			{
				cerr << "socket connect failed!" << endl;
			}
			else
			{
				string message;
				while (true)
				{
					cout << "请输入#：";
					getline(cin, message);

					write(sock_fd, message.c_str(), message.size());

					// 还就那个不能只写不读
					char buffer[NUM];
					int n = read(sock_fd, buffer, sizeof(buffer));
					if (n > 0)
					{
						buffer[n] = 0;
						cout << buffer << endl;
					}
					else
					{
						cout<<"服务器寄了，我也润了"<<endl;
						break;
					}
				}
			}
		}

		~Client()
		{
		}

	private:
		string _ip;
		uint16_t _port;

		int sock_fd;
	};

}
